package com.ruoyi.web.listener;

import com.gitee.deeround.jdbchelper.DbAction;
import com.ruoyi.core.util.SpringContextUtils;
import com.ruoyi.flow.entity.Constant;
import com.ruoyi.flow.entity.FireContext;
import com.ruoyi.flow.listener.FlowListener;
import com.ruoyi.web.domain.SysMod;
import com.ruoyi.web.service.SysModFactory;
import com.ruoyi.web.service.SysModService;

/**
 * 所有模型默认的流程监听
 */
public class DefaultFlowListener implements FlowListener {

    protected DbAction dbAction;
    protected SysModService sysModService;

    public DefaultFlowListener() {
        this.dbAction = SpringContextUtils.getBean(DbAction.class);
        this.sysModService = SpringContextUtils.getBean(SysModService.class);
    }


    @Override
    public void prepare(FireContext fireContext) {

    }

    @Override
    public void before(FireContext fireContext) {

        if (fireContext.getEvent().getId().equals(Constant.Event.START)) {
            SysModFactory.getSysModDataService(fireContext.getModId()).add(fireContext.getModId(), fireContext.getData());

            SysMod sysMod = sysModService.getById(fireContext.getModId());
            String sql = "update " + sysMod.getTableName() + " set instance_id=?,node_id=?,state=? where " + sysMod.getPrimaryKey() + "=?";
            dbAction.update(sql, new Object[]{
                    fireContext.getInstance().getInstanceId(),
                    fireContext.getTarget().getId(),
                    fireContext.getTarget().getState(),
                    fireContext.getData().getString(sysMod.getPrimaryKey())
            });
        }

    }

    @Override
    public void after(FireContext fireContext) {
        if ("delete".equals(fireContext.getEvent().getId())) {
            SysModFactory.getSysModDataService(fireContext.getModId()).delete(fireContext.getModId(), fireContext.getData());
            return;
        }

        SysModFactory.getSysModDataService(fireContext.getModId()).edit(fireContext.getModId(), fireContext.getData());

        SysMod sysMod = sysModService.getById(fireContext.getModId());
        String sql = "update " + sysMod.getTableName() + " set instance_id=?,node_id=?,state=? where " + sysMod.getPrimaryKey() + "=?";
        dbAction.update(sql, new Object[]{
                fireContext.getInstance().getInstanceId(),
                fireContext.getTarget().getId(),
                fireContext.getTarget().getState(),
                fireContext.getData().getString(sysMod.getPrimaryKey())
        });

    }
}
